/*
 * @Author: gonghairun
 * @Date: 2021-10-21 19:22:09
 * @LastEditors: gonghairun
 * @LastEditTime: 2022-08-10 09:54:47
 * @Description:
 */
import * as ExcelJS from "exceljs"
import FileSaver from "file-saver"

/**
 * @Author: gonghairun
 * @description: 导出
 * @param {*} columns - 表格列
 * @param {*} tableList - 表格数据源
 * @param {*} name - 表格名称
 * @return {*}
 */
export const exportExcel = (columns, tableList, name) => {
	const workbook = new ExcelJS.Workbook()
	workbook.creator = name
	workbook.lastModifiedBy = name
	workbook.created = new Date()
	workbook.modified = new Date()
	const worksheet = workbook.addWorksheet(name)
	worksheet.properties.defaultColWidth = 16 // 默认列宽
	worksheet.properties.defaultRowHeight = 16 // 默认行高

	let columnsNew = [],
		tableListNew = []
	// 遍历列
	columns.map(item => {
		columnsNew.push({
			name: item.label
		})
	})
	// 遍历表格源
	tableList.map((item, index) => {
		tableListNew.push([])
		columns.map(columnsItem => {
			tableListNew[index].push(item[columnsItem.exportProp ? columnsItem.exportProp : columnsItem.prop])
		})
	})
	// 设置表格数据以及列
	worksheet.addTable({
		name: "exportTable",
		ref: "A1",
		displayName: name,
		headerRow: true, // 在表格顶部显示标题
		filterButton: false, // 切换标题中的过滤器控件
		totalsRow: false, // 在表格底部显示总计
		columns: columnsNew,
		rows: tableListNew
	})
	workbook.xlsx.writeBuffer().then(buffer => {
		// eslint-disable-next-line no-undef
		FileSaver.saveAs(
			new Blob([buffer], {
				type: "application/octet-stream"
			}),
			`${name}.xlsx`
		)
	})
}
